import "./reset.css";
import dayjs from "dayjs";
import editForm from "../form/index.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { message } from "@/utils/message";
import userAvatar from "@/assets/user.jpg";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
// import ReCropperPreview from "@/components/ReCropperPreview";
// import type { FormItemProps } from "../utils/types";
import { getKeyList, isAllEmpty, hideTextAtIndex, deviceDetection, createFormData } from "@pureadmin/utils";
import { formUpload } from "@/api/mock";
import {
  getClientUserList,
  createClientUser,
  updateClientUser,
  deleteClientUser,
  toggleClientUserStatus,
  resetClientUserPassword
} from "@/api/client-user";
import { ElForm, ElInput, ElFormItem, ElProgress, ElMessageBox } from "element-plus";
import { type Ref, h, ref, toRaw, watch, computed, reactive, onMounted } from "vue";

export function useUser(tableRef: Ref) {
  const form = reactive({
    username: "",
    phone: "",
    enable: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // 上传头像信息
  // const avatarInfo = ref();
  const switchLoadMap = ref({});
  // 头像上传相关状态
  const imgSrc = ref("");
  const cropperBlob = ref();
  const originalFileName = ref("");
  const isShowAvatarDialog = ref(false);
  const { switchStyle } = usePublicHooks();
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const isMountedAndLoaded = ref(false); // Add this flag
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "用户编号",
      prop: "id",
      width: 90
    },
    {
      label: "用户头像",
      prop: "avatar",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.avatar || userAvatar}
          preview-src-list={Array.of(row.avatar || userAvatar)}
          class="w-[24px] h-[24px] rounded-full align-middle"
        />
      ),
      width: 90
    },
    {
      label: "账号",
      prop: "username",
      minWidth: 130
    },
    {
      label: "用户昵称",
      prop: "nickname",
      minWidth: 130
    },

    {
      label: "性别",
      prop: "gender",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.gender === 1 ? "" : row.gender === 2 ? "danger" : "info"}
          effect="plain"
        >
          {row.gender === 0 ? "未知" : row.gender === 1 ? "男" : row.gender === 2 ? "女" : "未知"}
        </el-tag>
      )
    },
    {
      label: "地区",
      prop: "location",
      minWidth: 120,
      cellRenderer: ({ row }) => {
        const location = [row.country, row.province, row.city].filter(Boolean).join(" ");
        return location || "未填写";
      }
    },
    {
      label: "微信绑定",
      prop: "wechat_status",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag size="small" type={row.openid ? "success" : "info"} effect="plain">
          {row.openid ? "已绑定" : "未绑定"}
        </el-tag>
      )
    },

    {
      label: "手机号码",
      prop: "phone",
      minWidth: 90,
      formatter: ({ phone }) => (phone ? hideTextAtIndex(phone, { start: 3, end: 6 }) : "")
    },
    {
      label: "状态",
      prop: "enable",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.enable}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={(val: number) => onChange(val, scope.row, scope.index)}
        />
      )
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "created_at",
      formatter: ({ created_at }) => (created_at ? dayjs(created_at).format("YYYY-MM-DD HH:mm:ss") : "")
    },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return ["h-[20px]!", "reset-margin", "text-gray-500!", "dark:text-white!", "dark:hover:text-primary!"];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();
  // 用户状态修改
  async function onChange(val: number, row: any, index: number) {
    console.log("用户状态修改：", val, row, index);
    // 如果页面还未完全加载完成，不触发确认对话框
    if (!isMountedAndLoaded.value) {
      return;
    }
    if (row.enable === val) return; // 如果状态没有改变，则不执行任何操作
    ElMessageBox.confirm(
      `确认要<strong>${val === 0 ? "停用" : "启用"}
      </strong><strong style='color:var(--el-color-primary)'>${row.username}</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        switchLoadMap.value[index] = Object.assign({}, switchLoadMap.value[index], {
          loading: true
        });
        try {
          await toggleClientUserStatus(row.id, { enable: val }); // 使用新的状态值 val
          message("已成功修改用户状态", { type: "success" });
        } catch (error) {
          message(`修改用户状态失败: ${error.message}`, { type: "error" });
          row.enable = val === 0 ? 1 : 0; // 回滚状态到 val 之前
        } finally {
          switchLoadMap.value[index] = Object.assign({}, switchLoadMap.value[index], {
            loading: false
          });
        }
      })
      .catch(() => {
        row.enable = val === 0 ? 1 : 0; // 回滚状态到 val 之前
      });
  }
  // 修改用户
  function handleUpdate(row) {
    console.log(row);
  }
  // 删除
  async function handleDelete(row) {
    try {
      await deleteClientUser(row.id);
      message(`已成功删除用户${row.username}`, { type: "success" });
      onSearch();
    } catch (error) {
      message(`删除用户失败: ${error.message}`, { type: "error" });
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    pagination.currentPage = 1;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }
  // 获取用户列表
  async function onSearch() {
    loading.value = true;
    try {
      const params = {
        ...toRaw(form),
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      // 移除空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === "" || params[key] === null || params[key] === undefined) {
          delete params[key];
        }
      });

      const response = await getClientUserList(params);
      // 直接使用response.data，它应该包含code和data字段
      if (response.data && Array.isArray(response.data.list)) {
        dataList.value = response.data.list || [];
        pagination.total = response.data.total || 0;
      } else {
        // 如果后端返回格式是 {code: 200, data: {list: [...], total: 10}}
        if (response.code === 200 && response.data) {
          dataList.value = response.data.list || [];
          pagination.total = response.data.total || 0;
        } else {
          message("获取用户列表失败", { type: "error" });
          dataList.value = [];
          pagination.total = 0;
        }
      }
    } catch (error) {
      message(`获取用户列表失败: ${error.message || error}`, { type: "error" });
      dataList.value = [];
      pagination.total = 0;
    } finally {
      loading.value = false; // Set loading to false immediately
    }
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: any) {
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          title,
          nickname: row?.nickname ?? "",
          username: row?.username ?? "",
          password: row?.password ?? "",
          phone: row?.phone ?? "",
          openid: row?.openid ?? "",
          unionid: row?.unionid ?? "",
          gender: row?.gender ?? 0,
          birthday: row?.birthday ?? "",
          country: row?.country ?? "",
          province: row?.province ?? "",
          city: row?.city ?? "",
          avatar: row?.avatar ?? "",
          enable: row?.enable ?? 1,
          description: row?.description ?? "",
          id: row?.id
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: ({ options }) =>
        h(editForm, {
          ref: formRef,
          formInline: options.props.formInline
        }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;

        async function chores() {
          try {
            if (title === "新增") {
              // 调用新增接口
              const createData = {
                username: curData.username,
                password: curData.password,
                phone: curData.phone,
                nickname: curData.nickname,
                openid: curData.openid,
                unionid: curData.unionid,
                birthday: curData.birthday,
                gender: curData.gender,
                country: curData.country,
                province: curData.province,
                city: curData.city,
                avatar: curData.avatar,
                description: curData.description,
                enable: curData.enable
              };
              await createClientUser(createData);
              message(`成功新增用户${curData.username}`, { type: "success" });
            } else {
              // 调用修改接口
              const updateData: any = {
                username: curData.username,
                phone: curData.phone,
                nickname: curData.nickname,
                openid: curData.openid,
                unionid: curData.unionid,
                birthday: curData.birthday,
                gender: curData.gender,
                country: curData.country,
                province: curData.province,
                city: curData.city,
                avatar: curData.avatar,
                description: curData.description,
                enable: curData.enable
              };
              // 如果有密码，则包含密码字段
              if (curData.password) {
                updateData.password = curData.password;
              }
              await updateClientUser(curData.id!, updateData);
              message(`成功修改用户${curData.username}`, { type: "success" });
            }
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          } catch (error) {
            message(`${title}用户失败: ${error.message || error}`, {
              type: "error"
            });
          }
        }

        FormRef.validate(valid => {
          if (valid) {
            chores();
          }
        });
      },
      closeCallBack: () => {
        // 关闭对话框时重置表单
        if (formRef.value?.resetForm) {
          formRef.value.resetForm();
        }
      }
    });
  }

  const cropRef = ref();
  const uploadRef = ref();
  const currentUploadUser = ref(null);

  /** 文件选择处理 */

  const _onAvatarChange = uploadFile => {
    originalFileName.value = uploadFile.raw.name;
    const reader = new FileReader();
    reader.onload = e => {
      imgSrc.value = e.target.result as string;
      isShowAvatarDialog.value = true;
    };
    reader.readAsDataURL(uploadFile.raw);
  };

  /** 关闭头像上传对话框 */
  const handleCloseAvatarDialog = () => {
    if (cropRef.value?.hidePopover) {
      cropRef.value.hidePopover();
    }
    if (uploadRef.value?.clearFiles) {
      uploadRef.value.clearFiles();
    }
    isShowAvatarDialog.value = false;
    imgSrc.value = "";
    cropperBlob.value = null;
    currentUploadUser.value = null;
  };

  /** 裁剪回调 */
  const onCropper = ({ blob }) => {
    cropperBlob.value = blob;
  };

  /** 提交头像 */
  const handleSubmitAvatar = async () => {
    if (!cropperBlob.value) {
      message("请先选择并裁剪图片", { type: "warning" });
      return;
    }

    try {
      const formData = createFormData({
        files: new File([cropperBlob.value], originalFileName.value)
      });

      const { code, data } = await formUpload(formData);

      if (code === 200) {
        const avatarUrl = import.meta.env.VITE_BASE_URL + data?.url;

        // 更新用户头像
        if (currentUploadUser.value) {
          try {
            await updateClientUser(currentUploadUser.value.id, {
              avatar: avatarUrl
            });
            message(`成功更新用户 ${currentUploadUser.value.username} 的头像`, {
              type: "success"
            });
            handleCloseAvatarDialog();
            onSearch(); // 刷新表格数据
          } catch (error) {
            message(`更新用户头像失败: ${error.message || error}`, {
              type: "error"
            });
          }
        }
      } else {
        message("上传头像失败", { type: "error" });
      }
    } catch (error) {
      message(`上传异常: ${error.message || error}`, { type: "error" });
    }
  };

  /** 上传头像 */
  function handleUpload(row) {
    currentUploadUser.value = row;
    // 触发文件选择
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";
    input.onchange = e => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        originalFileName.value = file.name;
        const reader = new FileReader();
        reader.onload = event => {
          imgSrc.value = event.target?.result as string;
          isShowAvatarDialog.value = true;
        };
        reader.readAsDataURL(file);
      }
    };
    input.click();
  }

  /** 绑定微信 */
  function handleBindWechat(row) {
    ElMessageBox.confirm(
      `确认要为用户 <strong style='color:var(--el-color-primary)'>${row.username}</strong> 绑定微信吗？`,
      "绑定微信",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        try {
          // TODO: 调用绑定微信接口
          // await bindWechat(row.id);
          message("微信绑定功能开发中，敬请期待", { type: "info" });
          // 成功后刷新表格数据
          // onSearch();
        } catch (error) {
          message(`绑定微信失败: ${error.message || error}`, { type: "error" });
        }
      })
      .catch(() => {
        // 用户取消操作
      });
  }

  /** 解绑微信 */
  function handleUnbindWechat(row) {
    ElMessageBox.confirm(
      `确认要为用户 <strong style='color:var(--el-color-primary)'>${row.username}</strong> 解绑微信吗？`,
      "解绑微信",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        try {
          // TODO: 调用解绑微信接口
          // await unbindWechat(row.id);
          message("微信解绑功能开发中，敬请期待", { type: "info" });
          // 成功后刷新表格数据
          // onSearch();
        } catch (error) {
          message(`解绑微信失败: ${error.message || error}`, { type: "error" });
        }
      })
      .catch(() => {
        // 用户取消操作
      });
  }

  watch(pwdForm, ({ newPwd }) => (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score));

  /** 重置密码 */
  function handleReset(row) {
    addDialog({
      title: `重置 ${row.username} 用户的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: true,
                  message: "请输入新密码",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </ElFormItem>
          </ElForm>
          <div class="my-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div class="w-[19vw]" style={{ marginLeft: idx !== 0 ? "4px" : 0 }}>
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p class="text-center" style={{ color: curScore.value === idx ? color : "" }}>
                  {text}
                </p>
              </div>
            ))}
          </div>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: async done => {
        // Added async keyword here
        ruleFormRef.value.validate(async valid => {
          // Added async keyword here
          if (valid) {
            // 表单规则校验通过
            message(`已成功重置 ${row.username} 用户的密码`, {
              type: "success"
            });
            console.log(`New password for ${row.username}: ${pwdForm.newPwd}`);
            // 调用重置用户密码接口
            try {
              await resetClientUserPassword(row.id, {
                password: pwdForm.newPwd
              });
              message(`已成功重置 ${row.username} 用户的密码`, {
                type: "success"
              });
              pwdForm.newPwd = ""; // 清空密码输入框
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            } catch (error) {
              message(`重置 ${row.username} 用户密码失败: ${error.message || error}`, { type: "error" });
              // 如果失败，不关闭弹窗，让用户重新尝试
            }
          }
        });
      }
    });
  }

  onMounted(async () => {
    await onSearch();
    isMountedAndLoaded.value = true; // Set flag after initial load
  });

  return {
    form,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate,
    handleDelete,
    handleUpload,
    handleReset,
    handleBindWechat,
    handleUnbindWechat,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    // 头像上传相关
    imgSrc,
    isShowAvatarDialog,
    cropRef,
    currentUploadUser,
    onCropper,
    handleSubmitAvatar,
    handleCloseAvatarDialog
  };
}
